package com.matrix.gallery.ui.wallpaper

import android.Manifest
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Environment
import android.view.Window
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ArrayUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.matrix.basecore.base.BaseActivity
import com.matrix.basecore.constant.Constant
import com.matrix.gallery.databinding.ActivityPreviewBinding
import com.matrix.gallery.ui.wallpaper.fragment.DownloadFragmentDialog
import com.matrix.gallery.ui.wallpaper.fragment.PreviewFragment
import com.matrix.gallery.ui.wallpaper.viewmodel.PreviewVM
import com.matrix.utils.common.WeChatShareHelper
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import kotlin.concurrent.thread
import kotlin.coroutines.CoroutineContext


@Route(path = Constant.ARouterPath.PreviewActivityPath)
class PreviewActivity : BaseActivity<ActivityPreviewBinding>() {

    private var position = 0
    private lateinit var datas: ArrayList<String>
    private var fragments: MutableList<Fragment> = mutableListOf()
    private val vm: PreviewVM by viewModels()
    override fun getViewBinding(): ActivityPreviewBinding {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        enableEdgeToEdge()
        return ActivityPreviewBinding.inflate(layoutInflater)
    }

    override fun initView() {
        position = intent.getIntExtra(Constant.ARouterString.POSITION, 0)
        datas = intent.getStringArrayListExtra(Constant.ARouterString.STRING_LIST)!!
        initFragment()
        mViewBinding.viewpager.adapter = VP2Adapter(fragments, this)
        mViewBinding.viewpager.currentItem = position
    }

    private val requestPermissionsLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->

        }

    private fun checkAndRequestStoragePermissions() {
        var permissionsToRequest: MutableList<String> = mutableListOf()
        // Android 14+ 需要的权限(读、写权限)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
                != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.READ_MEDIA_IMAGES)
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO)
                != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.READ_MEDIA_VIDEO);
            }
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED
                )
                != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED);
            }
        }
        var arr: Array<String> = Array(permissionsToRequest.size) {
            permissionsToRequest[it]
        }
        requestPermissionsLauncher.launch(arr)
    }

    override fun initListener() {
        mViewBinding.ivBack.setOnClickListener {
            finish()
        }

        mViewBinding.viewpager.setPageTransformer { page, position ->
            run {
                mViewBinding.tvCount.text =
                    String.format("%s", mViewBinding.viewpager.currentItem + 1) + "/" + datas.size
            }
        }
        mViewBinding.ivWise.setOnClickListener {
            requestedOrientation =
                if (getResources().configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    //                ScreenUtils.setPortrait(this)
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                } else {
                    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                }
        }
        mViewBinding.ivMore.setOnClickListener {
            checkAndRequestStoragePermissions()
            DownloadFragmentDialog(object : DownloadFragmentDialog.OnClickListener {
                override fun onClick(position: Int) {
                    downloadImage(datas[mViewBinding.viewpager.currentItem], position)
                }
            }).show(supportFragmentManager, "")
        }
    }

    private fun downloadImage(url: String, position: Int) {
        when (position) {
            1 -> {
                download(vm.getDownloads(url))
            }

            2 -> {
                WeChatShareHelper.shareText2WechatFriend(this, url)
            }

            3 -> {
                val shareIntent = Intent(Intent.ACTION_SEND)
                shareIntent.setType("text/plain")
                shareIntent.putExtra(Intent.EXTRA_TEXT, url)
                startActivity(shareIntent)
            }
        }
    }

    private fun download(call: Call<ResponseBody>) {
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(
                call: Call<ResponseBody>,
                response: Response<ResponseBody>
            ) {
                var result = ""
                lifecycleScope.launch {
                    try {
                        var iStream: InputStream = response.body()!!.byteStream()
                        var distPath =
                            File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + File.separator + Constant.ImagePath)
                        if (!distPath.exists()) {
                            distPath.mkdirs()
                        }
                        var file = File(
                            distPath,
                            System.currentTimeMillis().toString() + ".png"
                        )
                        var fos = FileOutputStream(file);
                        fos.use { _ ->
                            iStream.use { s ->
                                val buffer = ByteArray(1024)
                                var bytesRead: Int
                                while (s.read(buffer).also { bytesRead = it } != -1) {
                                    fos.write(buffer, 0, bytesRead)
                                }
                            }
                        }
                        result = "下载成功：${distPath.path}"
                    } catch (e: Exception) {
                        e.stackTrace
                        LogUtils.i(e.stackTrace)
                        result = "下载失败：${e.stackTrace}"
                    }
                }
                ToastUtils.showShort(result)
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                ToastUtils.showShort("error：${t.stackTrace}")
            }
        })
    }

//    private fun download(call: Call<ResponseBody>) {
//        call.enqueue(object : Callback<ResponseBody> {
//            override fun onResponse(
//                call: Call<ResponseBody>,
//                response: Response<ResponseBody>
//            ) {
//                thread {
//                    try {
//                        var iStream: InputStream = response.body()!!.byteStream()
//                        var distPath =
//                            File(Environment.getExternalStorageDirectory().path + File.separator + Constant.ImagePath)
//                        if (!distPath.exists()) {
//                            distPath.mkdirs()
//                        }
//                        var file = File(
//                            distPath,
//                            System.currentTimeMillis().toString() + ".png"
//                        )
//                        var fos = FileOutputStream(file);
//                        fos.use { _ ->
//                            iStream.use { s ->
//                                val buffer = ByteArray(1024)
//                                var bytesRead: Int
//                                while (s.read(buffer).also { bytesRead = it } != -1) {
//                                    fos.write(buffer, 0, bytesRead)
//                                }
//                            }
//                        }
//                        runOnUiThread {
//                            ToastUtils.showShort("下载成功：" + distPath.path)
//                        }
//                    } catch (e: Exception) {
//                        e.stackTrace
//                        runOnUiThread {
//                            ToastUtils.showShort("下载失败：" + e.stackTrace)
//                        }
//                    }
//                }
//            }
//
//            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
//
//            }
//        })
//    }

    private fun initFragment() {
        for (item in datas) {
            fragments.add(PreviewFragment(item))
        }
    }

    class VP2Adapter(fragments: MutableList<Fragment>, fragmentActivity: FragmentActivity) :
        FragmentStateAdapter(fragmentActivity) {
        private var fragments: MutableList<Fragment> = fragments

        override fun getItemCount(): Int {
            return fragments.size
        }

        override fun createFragment(position: Int): Fragment {
            return fragments[position]
        }
    }
}
